<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, h, ref } from 'vue'
import { Page, useVbenModal } from '@vben/common-ui'
import { Button, message, Tag, Popconfirm, Spin } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getOrderDeductionList, exportExpiredData, importFile, getInitData, approvalOrderDeduction, againstOrderDeduction, deleteOrderDeduction } from '#/api/orderDeduction'
import { getSupplyList } from '#/api/common'
import { useDebounceFn } from '@vueuse/core'
import Form from './modules/form.vue'
import dayjs from 'dayjs'
import { AntPlusOutlined, AntDeleteOutlined, AntCheckOutlined, AntCloseOutlined, AntDownloadOutlined, AntUploadOutlined } from '@vben/icons'
import { useRouter } from 'vue-router'
interface RowType {
  [key: string]: any
}

const router = useRouter()
const selectedRows = ref<RowType[]>([])
const formData = ref<any>({})
const keyword = ref({
  supply_id: '',
})

// 获取供应商选项
const fetchSupplyOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getSupplyList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.supply_id,
    select: true,
  })
  return list.map((item: any) => ({ label: item.SupplyNa, value: item.id }))
}

// 获取选中行的ID数组
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.id)
}

// 审核按钮判断
const isDisabledApproval = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.posted >= 1)
})

// 反审按钮判断
const isDisabledAgainst = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.posted === 0)
})

// 默认排序
const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'id',
  order: 'desc',
}

const fetchData = async () => {
  gridApi.reload()
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'id',
      label: '编号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'posted',
      label: '审核状态',
      operator: '=',
      componentProps: {
        options: [
          { label: '未审核', value: 0 },
          { label: '已审核', value: 1 },
        ],
        placeholder: '请选择',
        allowClear: true,
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'order_date',
      label: '扣款日期',
      operator: 'RANGE',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'ApiSelect',
      fieldName: 'supply_id',
      label: '供应商',
      operator: '=',
      componentProps: () => ({
        api: fetchSupplyOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.supply_id = value
        }, 300),
        params: { keyword: keyword.value.supply_id || undefined },
        allowClear: true,
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.supply_id = ''
        },
      }),
    },
    {
      component: 'Select',
      fieldName: 'type',
      label: '类型',
      operator: '=',
      componentProps: {
        options: [
          { label: '其他扣款', value: 1 },
          { label: '代卖', value: 2 },
          { label: '大货逾期扣款', value: 3 },
          { label: '物料逾期扣款', value: 4 },
        ],
        placeholder: '请选择',
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'source_type',
      label: '扣款性质',
      operator: '=',
      componentProps: {
        options: [
          { label: 'CMT', value: 1 },
          { label: 'FOB', value: 2 },
        ],
        placeholder: '请选择',
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'fk_sn',
      label: '调整单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'goods_no',
      label: '货号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'merchandiser',
      label: '跟单人',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'reason',
      label: '扣款事由',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'createAdmin*realname',
      label: '创建人',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    isHover: true,
  },
  columnConfig: { useKey: true },
  columns: [
    { type: 'checkbox', width: 50, fixed: 'left' },
    { field: 'id', width: 80, title: '编号', fixed: 'left' },
    {
      field: 'posted',
      width: 100,
      title: '审核状态',
      fixed: 'left',
      slots: { default: 'postStatus' },
    },
    {
      field: 'order_date',
      width: 120,
      title: '订单日期',
      fixed: 'left',
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD')
        }
        return '-'
      },
    },
    {
      field: 'supply.SupplyNa',
      width: 120,
      title: '供应商',
      fixed: 'left',
    },
    {
      field: 'type',
      width: 100,
      title: '类型',
      slots: { default: 'typeStatus' },
    },
    {
      field: 'source_type',
      width: 100,
      title: '扣款性质',
      slots: { default: 'sourceTypeStatus' },
    },
    { field: 'fk_sn', width: 150, title: '调整单号' },
    { field: 'sale_date', width: 150, title: '代卖截止日期' },
    {
      field: 'reason_show_text',
      width: 450,
      title: '扣款事由/代卖原因',
      showOverflow: 'tooltip',
    },
    { field: 'price', width: 150, title: '扣款金额' },
    { field: 'mark', width: 120, title: '备注' },
    { field: 'remark', width: 180, title: '备注2' },
    { field: 'goods_no', width: 120, title: '货号' },
    { field: 'merchandiser', width: 120, title: '跟单人' },
    { field: 'audit_admin_info', width: 220, title: '审核人' },
    { field: 'update_admin_info', width: 220, title: '修改人' },
    { field: 'create_admin_info', width: 220, title: '创建人' },
    {
      field: 'createAdmin.realname',
      width: 220,
      title: '创建人',
      visible: false,
    },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 100,
    },
  ],
  rowStyle({ row }) {
    if (!(row.post_time && Number(row.post_time) > 0)) {
      return { color: 'red' }
    }
  },
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: { pageSize: 20 },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const { list, total } = await getOrderDeductionList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        })
        return { items: list, total: total }
      },
    },
    sort: true,
  },
  sortConfig: { defaultSort, remote: true },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'order_deduction_list',
  customConfig: {
    storage: true,
  },
}

// 获取审核状态标签颜色和文本
const getPostStatusColor = (posted: number) => {
  return posted === 1 ? 'success' : 'warning'
}

const getPostStatusText = (posted: number) => {
  return posted === 1 ? '已审核' : '未审核'
}

// 获取类型标签颜色和文本
const getTypeColor = (type: number) => {
  const colors = { 1: '#f56c6c', 2: '#ffcf47', 3: '#ff3f33', 4: '#00a9ff' }
  return colors[type as keyof typeof colors] || '#e547af'
}

const getTypeText = (type: number) => {
  const types = {
    1: '其他扣款',
    2: '代卖',
    3: '大货逾期扣款',
    4: '物料逾期扣款',
  }
  return types[type as keyof typeof types] || type
}

// 获取扣款性质标签颜色和文本
const getSourceTypeColor = (sourceType: number) => {
  return sourceType === 1 ? '#4e69fd' : '#03df6d'
}

const getSourceTypeText = (sourceType: number) => {
  return sourceType === 1 ? 'CMT' : 'FOB'
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
  },
})

// 导出功能
const handleExport = async () => {
  const hide = message.loading('正在导出...', 0)
  try {
    const search = await gridApi.formApi.getFiltersValues()
    await exportExpiredData({ search, export: true }).then((res) => {
      message.success('创建导出任务成功，请移步导出中心下载')
      router.push({ name: 'downloadRecord' })
    })
  } catch (e) {
    // message.error('导出失败');
  } finally {
    hide()
  }
}

// 导入功能
const handleImport = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.click()
  input.addEventListener('change', function (e: any) {
    if (e.target.files.length === 0) {
      return
    }
    const file = e.target.files[0]
    const formData = new FormData()
    formData.append('file', file)

    const hide = message.loading('上传中...', 0)
    importFile(formData)
      .then((res) => {
        hide()
        if (res.isSuccess === 1) {
          message.success('导入成功')
        } else {
          message.error('导入失败')
        }
        gridApi.query()
      })
      .catch(() => {
        hide()
        message.error('导入失败')
      })
  })
}

// 下载模板
const handleDownloadTemplate = () => {
  const link = document.createElement('a')
  link.href = '/static/template/扣款订单导入模板.xlsx'
  link.download = '扣款订单导入模板.xlsx'
  link.click()
}

// 事件处理
const handleshowFormData = (row: RowType) => {
  FormModalApi.setData({
    info: row,
  }).open()
}

const [FormModal, FormModalApi] = useVbenModal({
  connectedComponent: Form,
})

const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要删除的数据')
    return
  }
  const hideLoading = message.loading({
    content: '删除中...',
    duration: 0,
    key: 'action_process_msg',
  })

  deleteOrderDeduction({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: '删除成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理审核操作
const handleApproval = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要审核的数据')
    return
  }
  const hideLoading = message.loading({
    content: '审核中...',
    duration: 0,
    key: 'action_process_msg',
  })

  approvalOrderDeduction({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: '审核成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理反审操作
const handleAgainst = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要反审的数据')
    return
  }

  const hideLoading = message.loading({
    content: '反审中...',
    duration: 0,
    key: 'action_process_msg',
  })

  againstOrderDeduction({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: '反审成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleshowFormData({})">
          <AntPlusOutlined />
          新建
        </Button>
        <Popconfirm
          :disabled="isDisabledApproval"
          title="确认删除"
          :description="`确定要删除选中的 ${selectedRows.length} 条数据吗？此操作不可恢复。`"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete"
          @cancel="() => {}"
        >
          <Button class="mr-2" type="primary" danger :disabled="isDisabledApproval">
            <AntDeleteOutlined />
            删除
          </Button>
        </Popconfirm>

        <Popconfirm :disabled="isDisabledApproval" title="确认审核" :description="`确定要审核选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleApproval" @cancel="() => {}">
          <Button type="ghost" :class="['mr-2', isDisabledApproval ? 'ant-btn-disabled' : 'bg-[#24b916] text-white hover:opacity-75']" :disabled="isDisabledApproval">
            <AntCheckOutlined />
            审核
          </Button>
        </Popconfirm>
        <Popconfirm :disabled="isDisabledAgainst" title="确认反审" :description="`确定要反审选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleAgainst" @cancel="() => {}">
          <Button type="ghost" :class="['mr-2', isDisabledAgainst ? 'ant-btn-disabled' : 'bg-[#f56c6c] text-white hover:opacity-75']" :disabled="isDisabledAgainst">
            <AntCloseOutlined />
            反审
          </Button>
        </Popconfirm>

        <Popconfirm title="确认导出" description="确定要导出数据吗？" ok-text="确认" cancel-text="取消" @confirm="handleExport" @cancel="() => {}">
          <Button class="mr-2" type="ghost" :class="['bg-[#e6a23c] text-white hover:opacity-75']">
            <AntDownloadOutlined />
            导出
          </Button>
        </Popconfirm>

        <Button class="mr-2" type="primary" @click="handleImport">
          <AntUploadOutlined />
          导入
        </Button>

        <Popconfirm title="确认下载模板" description="确定要下载导入模板吗？" ok-text="确认" cancel-text="取消" @confirm="handleDownloadTemplate" @cancel="() => {}">
          <Button class="mr-2" type="primary">
            <AntDownloadOutlined />
            下载模板
          </Button>
        </Popconfirm>
      </template>

      <template #postStatus="{ row }">
        <Tag :color="getPostStatusColor(row.posted)">
          {{ getPostStatusText(row.posted) }}
        </Tag>
      </template>

      <template #typeStatus="{ row }">
        <Tag :color="getTypeColor(row.type)">
          {{ getTypeText(row.type) }}
        </Tag>
      </template>

      <template #sourceTypeStatus="{ row }">
        <Tag :color="getSourceTypeColor(row.source_type)">
          {{ getSourceTypeText(row.source_type) }}
        </Tag>
      </template>

      <template #operation="{ row }">
        <Button class="mr-2" type="primary" size="small" @click.stop="handleshowFormData(row)">编辑</Button>
      </template>
    </Grid>
    <FormModal @fetch-data="fetchData" />
  </Page>
</template>
